package com.hema.auction.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.hema.auction.R;
import com.hema.auction.base.BaseActivity;
import com.hema.auction.bean.AddressInfo;
import com.hema.auction.bean.RegionInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.GetJsonDataUtil;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.view.TitleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 收货信息
 * author by john
 */

public class AddressActivity extends BaseActivity {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_mark)
    EditText etMark;
    @BindView(R.id.et_qq)
    EditText etQQ;
    @BindView(R.id.et_alipay_account)
    EditText etALipayAccount;
    @BindView(R.id.et_alipay_name)
    EditText etALipayName;
    private ArrayList<RegionInfo> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 100;
    private static final int MSG_LOAD_SUCCESS = MSG_LOAD_DATA + 1;
    private static final int MSG_LOAD_FAILED = MSG_LOAD_SUCCESS + 1;
    private Thread thread;
    private boolean isLoaded = false;

    private AddressInfo info;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        getDefaultHandler().sendEmptyMessage(MSG_LOAD_DATA);
        showProgressDialog("正在获取收货地址信息");
        HttpManager.getInstance(this).getAddress(this);
        titleView.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (((TextView) titleView.getRightView()).getText().toString().equals("重新获取地址")) {
                    showProgressDialog("正在获取收货地址信息");
                    HttpManager.getInstance(AddressActivity.this).getAddress(AddressActivity
                            .this);
                } else {
                    editAddress();
                }
            }
        });
    }

    /**
     * 更新地址信息
     */
    private void editAddress() {
        if (etName.getText().toString().trim().length() == 0) {
            showToastSafe("请输入收货人姓名");
        } else if (etPhone.getText().toString().trim().length() == 0) {
            showToastSafe("请输入收件人手机号");
        } else if (etQQ.getText().toString().trim().length() == 0) {
            showToastSafe("请输入QQ号");
        } else if (etALipayAccount.getText().toString().trim().length() == 0) {
            showToastSafe("请输入支付宝账号");
        } else if (etALipayName.getText().toString().trim().length() == 0) {
            showToastSafe("请输入支付宝姓名");
        } else if (tvArea.getText().toString().trim().length() == 0) {
            showToastSafe("请选择所在地区");
        } else if (etAddress.getText().toString().trim().length() == 0) {
            showToastSafe("请输入具体地址");
        } else {
            showProgressDialog();
            info.setName(etName.getText().toString().trim());
            info.setPhone(etPhone.getText().toString().trim());
            info.setArea(tvArea.getText().toString().trim());
            info.setAddress(etAddress.getText().toString().trim());
            info.setRemark(etMark.getText().toString().trim());
            info.setQqNumber(etQQ.getText().toString().trim());
            info.setZfbNumber(etALipayAccount.getText().toString().trim());
            info.setZfbName(etALipayName.getText().toString().trim());
            HttpManager.getInstance(this).editAddress(info, this);
        }

    }


    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_EDIT_ADDRESS:
                try {
                    if (result.getInt("errcode") == 0) {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(Constant.EXTRA_ADDRESS_INFO, info);
                        intent.putExtras(bundle);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_ADDRESS:
                try {
                    if (result.getInt("errcode") == 0) {
                        info = new Gson().fromJson(result.getJSONObject("data").toString(), AddressInfo.class);
                        etName.setText(info.getName());
                        etName.setSelection(info.getName().length());
                        etPhone.setText(info.getPhone());
                        tvArea.setText(info.getArea());
                        etAddress.setText(info.getAddress());
                        etMark.setText(info.getRemark());
                        etQQ.setText(info.getQqNumber());
                        etALipayAccount.setText(info.getZfbNumber());
                        etALipayName.setText(info.getZfbName());
                    } else {
                        titleView.setRightText("获取收货信息");
                        showToastSafe(result);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    titleView.setRightText("获取收货信息");
                }
                break;
        }
    }

    @Override
    protected void onHandleMessage(Message msg) {
        switch (msg.what) {
            case MSG_LOAD_DATA:
                if (thread == null) {//如果已创建就不再重新创建子线程了

                    thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 写子线程中的操作,解析省市区数据
                            initJsonData();
                        }
                    });
                    thread.start();
                }
                break;

            case MSG_LOAD_SUCCESS:
                isLoaded = true;
                break;

            case MSG_LOAD_FAILED:
                break;

        }
    }

    @OnClick({R.id.tv_area})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_area:
                if (isLoaded) {
                    Utils.hideKeyboard(this);
                    onAddressPicker();
                } else {
                    showToastSafe("正在加载地区数据");
                }
                break;
        }
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<RegionInfo> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        getDefaultHandler().sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<RegionInfo> parseData(String result) {//Gson 解析
        ArrayList<RegionInfo> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                RegionInfo entity = gson.fromJson(data.optJSONObject(i).toString(), RegionInfo.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            getDefaultHandler().sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    public void onAddressPicker() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()
                        + " " + options2Items.get(options1).get(option2)
                        + " " + options3Items.get(options1).get(option2).get(options3);
                tvArea.setText(tx);
            }
        }).setSubmitColor(getResources().getColor(R.color.colorPrimary)).setCancelColor(getResources().getColor(R.color.colorPrimary)).build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);
        pvOptions.show();
    }


}
